"""
Pydantic V2 的模型解析器
"""

from types import GenericAlias
from typing import (
    Dict,
    List,
    Optional,
    cast,
)

from pydantic import BaseModel
from pydantic.fields import FieldInfo


def parse_v2_model_fields(
    model: type[BaseModel],
    field_dic: Dict[str, str],
    parent_field_name: Optional[str] = None,
    connector: str = ".",
) -> None:
    """
    解析 Pydantic 模型字段数据

    Args:
        model: 模型（BaseModel 的子类）
        field_dic: 解析后的字段字典
        parent_field_name: 父级字段名称
        connector: 字段字典连接符

    """

    model_fields: Dict[str, FieldInfo] = model.model_fields

    for field_name, field in model_fields.items():
        field_title: str = field.title or field_name
        field_name_list: List[str] = [field_name]
        field_title_list: List[str] = [field_title]

        if parent_field_name is not None:
            field_name_list.insert(0, parent_field_name)
            _field_title: Optional[str] = field_dic.get(parent_field_name)

            if _field_title:
                field_title_list.insert(0, _field_title)

        field_dic[connector.join(field_name_list)] = connector.join(field_title_list)

        # 优化类型判断和处理逻辑
        field_annotations: List[type] = (
            list(cast(GenericAlias, field.annotation).__args__)
            if isinstance(field.annotation, GenericAlias)
            else [field.annotation]
        )

        # 处理嵌套的 BaseModel
        for annotation in field_annotations:
            if not issubclass(annotation, BaseModel):
                continue

            parse_v2_model_fields(annotation, field_dic, field_name)
